package com.online.questionnaire.controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.online.questionnaire.common.ErrorCode;
import com.online.questionnaire.common.PageParam;
import com.online.questionnaire.common.R;
import com.online.questionnaire.common.ResultUtils;
import com.online.questionnaire.exception.BusinessException;
import com.online.questionnaire.exception.ThrowUtils;
import com.online.questionnaire.model.Questions;
import com.online.questionnaire.model.Surveys;
import com.online.questionnaire.model.TemplateAudit;
import com.online.questionnaire.model.User;
import com.online.questionnaire.model.dto.SurveysDTO;
import com.online.questionnaire.service.QuestionsService;
import com.online.questionnaire.service.SurveysService;
import com.online.questionnaire.service.TemplateAuditService;
import com.online.questionnaire.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.online.questionnaire.constant.UserConstant.ADMIN_ROLE;

@RestController
@Slf4j
@RequestMapping("/template")
@Tag(name = "模板接口")
public class TemplateController {

    @Resource
    private TemplateAuditService templateService;
    @Resource
    private SurveysService surveysService;
    @Resource
    private QuestionsService questionsService;
    @Resource
    private UserService userService;

    /**
     * 分页查询 模板
     * @param surveys
     * @param request
     * @return
     */
    @PostMapping("/page")
    public R<IPage<Surveys>> page(PageParam param,@RequestBody Surveys surveys, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            ThrowUtils.notLoginError();
        }
        if (param.getPage() == null || param.getPage() <= 0){
            param.setPage(1);
        }
        if (param.getSize() == null || param.getSize() <= 0 || param.getSize() > 50){
            param.setSize(50);
        }
        LambdaQueryWrapper<Surveys> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Surveys::getTemplateNum);
        //仅限模板问卷
        queryWrapper.eq(Surveys::getIsTemplate,1);

        //如果是用户只能查看发布状态的问卷模板 管理员可以自由选择
        if (surveys.getStatus() != null){
            if (loginUser.getUserRole().equals(ADMIN_ROLE)){
                queryWrapper.eq(Surveys::getStatus,surveys.getStatus());
            }else{
                queryWrapper.eq(Surveys::getStatus,1);
            }
        }

        if (StringUtils.isNotBlank(surveys.getTitle()) || StringUtils.isNotBlank(surveys.getTags())){
            queryWrapper.and(q -> {
                boolean isOr  = false;
                if (StringUtils.isNotBlank(surveys.getTitle())){
                    q.like(Surveys::getTitle,surveys.getTitle());
                    isOr = true;
                }
                if (StringUtils.isNotBlank(surveys.getTags())){
                    //括号 (tags like '%测试%' or tags like '%模板%')
                    try{
                        List<String> list = JSONUtil.toList(surveys.getTags(), String.class);
                        if (!list.isEmpty()){
                            q.or(isOr).like(Surveys::getTags,list.get(0));
//                            q.or(isOr).and(tagQuery -> {
//                                if (list.size() == 1){
//                                    tagQuery.like(Surveys::getTags,list.get(0));
//                                }else{
//                                    //去重
//                                    List<String> distinctTags = list.stream().distinct().toList();
//                                    // 模糊查询标签
//                                    tagQuery.and(wrapper -> {
//                                        for (String tag : distinctTags) {
//                                            wrapper.like(Surveys::getTags, tag).or();
//                                        }
//                                    });
//                                }
//                            });
                        }

                    }catch (Exception e){
                        ThrowUtils.throwIf(true,ErrorCode.PARAMS_ERROR,"标签格式错误");
                    }
                }


            });
        }

        //按照使用次数排序
        queryWrapper.orderByDesc(Surveys::getTemplateNum);

        Page<Surveys> pageInfo = surveysService.page(new Page<>(param.getPage(),param.getSize()),queryWrapper);
        //查询每题的题目数量
        for (Surveys surveys1 : pageInfo.getRecords()){
            LambdaQueryWrapper<Questions> questionsQueryWrapper = new LambdaQueryWrapper<>();
            questionsQueryWrapper.eq(Questions::getSurveyid,surveys1.getId());
            surveys1.setQuestionNum((int) questionsService.count(questionsQueryWrapper));

            //查询创建用户
            User user = userService.getById(surveys1.getCreateuserid());
            if (user != null){
                surveys1.setCreateUserName(user.getUserName());
            }
        }
        return ResultUtils.success(pageInfo);
    }
    /**
     * 分页获取热门模板
     * hotTemplate
     */
    @GetMapping("/hotTemplate")
    public R<IPage<Surveys>> hotTemplate(PageParam param){
        if (param.getPage() == null || param.getPage() <= 0){
            param.setPage(1);
        }
        if (param.getSize() == null || param.getSize() <= 0 || param.getSize() > 50){
            param.setSize(10);
        }
        LambdaQueryWrapper<Surveys> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Surveys::getIsTemplate,1);
        queryWrapper.eq(Surveys::getStatus,1);
        queryWrapper.orderByDesc(Surveys::getTemplateNum);
        Page<Surveys> pageInfo = surveysService.page(new Page<>(param.getPage(),param.getSize()),queryWrapper);
        for (Surveys surveys1 : pageInfo.getRecords()){
            LambdaQueryWrapper<Questions> questionsQueryWrapper = new LambdaQueryWrapper<>();
            questionsQueryWrapper.eq(Questions::getSurveyid,surveys1.getId());
            surveys1.setQuestionNum((int) questionsService.count(questionsQueryWrapper));

            //查询创建用户
            User user = userService.getById(surveys1.getCreateuserid());
            if (user != null){
                surveys1.setCreateUserName(user.getUserName());
            }
        }
        return ResultUtils.success(pageInfo);

    }
    /**
     * 查看审批列表
     */
    @GetMapping("/auditList")
    public R<IPage<TemplateAudit>> auditList(PageParam param,Integer status,HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            ThrowUtils.notLoginError();
        }
        if (param.getPage() == null || param.getPage() <= 0){
            param.setPage(1);
        }
        if (param.getSize() == null || param.getSize() <= 0 || param.getSize() > 50){
            param.setSize(50);
        }
        //只能管理员访问
        if (!ADMIN_ROLE.equals(loginUser.getUserRole())){
            ThrowUtils.throwIf(true,ErrorCode.NO_AUTH_ERROR);
        }
        LambdaQueryWrapper<TemplateAudit> queryWrapper = new LambdaQueryWrapper<>();
        //按照状态筛选  -1为查询全部
        if (status > -1){
            queryWrapper.eq(TemplateAudit::getStatus,status);
        }
        // 按照未审核状态排序
        queryWrapper.orderByAsc(TemplateAudit::getStatus);
        // 按照最近创建时间排序
        queryWrapper.orderByDesc(TemplateAudit::getCreateTime);
        Page<TemplateAudit> pageInfo = templateService.page(new Page<>(param.getPage(),param.getSize()),queryWrapper);
        //问卷名称缓存
        Map<Long, String> surveyTitleMap = new HashMap<>();
        for (TemplateAudit templateAudit : pageInfo.getRecords()){
            //查询用户名
            if (templateAudit.getUserId() != null){
                User user = userService.getById(templateAudit.getUserId());
                if (user != null){
                    templateAudit.setUserName(user.getUserName());
                }
            }
            //查询审核用户名
            if (templateAudit.getAuditUserId() != null){
                User user = userService.getById(templateAudit.getAuditUserId());
                if (user != null){
                    templateAudit.setAuditUserName(user.getUserName());
                }
            }
            //查询问卷名
            if (!surveyTitleMap.containsKey(templateAudit.getSurveyId())){
                Surveys surveys = surveysService.getById(templateAudit.getSurveyId());
                if (surveys != null){
                    surveyTitleMap.put(templateAudit.getSurveyId(),surveys.getTitle());
                    templateAudit.setSurveyTitle(surveyTitleMap.get(templateAudit.getSurveyId()));
                }
            }else{
               templateAudit.setSurveyTitle(surveyTitleMap.get(templateAudit.getSurveyId()));
            }
        }

        return ResultUtils.success(pageInfo);
    }
    /**
     * 引用模板
     */
    @PostMapping("/copyTemplate")
    public R<Boolean> copyTemplate(@RequestBody SurveysDTO survey, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            ThrowUtils.notLoginError();
        }
        if (survey == null){
            ThrowUtils.paramsError("参数错误");
        }
        boolean b = surveysService.copyTemplate(survey, loginUser);
        if (!b){
            return ResultUtils.error(ErrorCode.OPERATION_ERROR,"复制失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 申请上传模板
     */
    @PostMapping("/applyTemplate")
    public R<Boolean> applyTemplate(@RequestBody TemplateAudit templateAudit, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            ThrowUtils.notLoginError();
        }
        if (templateAudit == null){
            ThrowUtils.paramsError("参数错误");
        }
        //检查问卷是否存在
        Surveys surveys = surveysService.getById(templateAudit.getId());
        ThrowUtils.throwIf(surveys == null,ErrorCode.PARAMS_ERROR,"问卷不存在");
        //检查问卷是否已经有待审核的记录
        LambdaQueryWrapper<TemplateAudit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TemplateAudit::getSurveyId,templateAudit.getId());
        queryWrapper.eq(TemplateAudit::getStatus,0);
        if (templateService.count(queryWrapper) > 0){
            return ResultUtils.error(ErrorCode.OPERATION_ERROR,"该问卷已经有待审核的记录");
        }

        TemplateAudit newTemplateAudit = new TemplateAudit();

        newTemplateAudit.setSurveyId(templateAudit.getId());
        newTemplateAudit.setUserId(loginUser.getId());
        newTemplateAudit.setStatus(0);
        boolean save = templateService.save(newTemplateAudit);
        if (!save){
            return ResultUtils.error(ErrorCode.OPERATION_ERROR,"申请失败");
        }else{
            return ResultUtils.success(save);
        }
    }
    /**
     * 管理员审核接口
     */
    @PostMapping("/auditTemplate")
    @Transactional
    public R<Boolean> auditTemplate(@RequestBody TemplateAudit templateAudit, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            ThrowUtils.notLoginError();
        }
        if (templateAudit == null){
            ThrowUtils.paramsError("参数错误");
        }
        //检查权限
        if (!ADMIN_ROLE.equals(loginUser.getUserRole())){
            ThrowUtils.throwIf(true,ErrorCode.NO_AUTH_ERROR);
        }
        TemplateAudit audit = new TemplateAudit();
        audit.setId(templateAudit.getId());
        audit.setStatus(templateAudit.getStatus());
        audit.setAuditUserId(loginUser.getId());

        TemplateAudit byId = templateService.getById(templateAudit.getId());

        //如果为审核通过 新增一条模板
        if (audit.getStatus() == 1){
            SurveysDTO surveys = surveysService.getDTOById(templateAudit.getSurveyId());
            if (surveys != null){
                surveysService.addTemplate(surveys, byId.getUserId());
            }
        }
        boolean b = templateService.updateById(audit);
        if (!b){
            return ResultUtils.error(ErrorCode.OPERATION_ERROR,"审核失败");
        }
        return ResultUtils.success(b);
    }

    /**
     * 管理员新增模板
     */
    @PostMapping("/addTemplate")
    public R<SurveysDTO> addTemplate(@RequestBody SurveysDTO surveysDTO, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            ThrowUtils.notLoginError();
        }
        if (surveysDTO == null){
            ThrowUtils.paramsError("参数错误");
        }
        //检查权限
        if (!ADMIN_ROLE.equals(loginUser.getUserRole())){
            ThrowUtils.throwIf(true,ErrorCode.NO_AUTH_ERROR);
        }
        SurveysDTO surveysDTO1 = surveysService.addTemplate(surveysDTO, loginUser.getId());
        return ResultUtils.success(surveysDTO1);
    }

    /**
     * 管理员自行、保存模板
     */
    @PostMapping("/saveTemplate")
    public R<SurveysDTO> saveTemplate(@RequestBody SurveysDTO surveysDTO, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            ThrowUtils.notLoginError();
        }
        if (surveysDTO == null){
            ThrowUtils.paramsError("参数错误");
        }
        //检查权限
        if (!ADMIN_ROLE.equals(loginUser.getUserRole())){
            ThrowUtils.throwIf(true,ErrorCode.NO_AUTH_ERROR);
        }
        SurveysDTO surveysDTO1 = surveysService.updateSurveys(surveysDTO, loginUser.getId());
        return ResultUtils.success(surveysDTO1);
    }

    /**
     * 删除模板 
     * 仅限管理员操作
     * 
     */
    @PostMapping("/deleteTemplate")
    public R<Boolean> deleteTemplate(@RequestBody String surveyId, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            ThrowUtils.notLoginError();
        }
        if (surveyId == null){
            ThrowUtils.paramsError("参数错误");
        }
        //检查权限
        if (!ADMIN_ROLE.equals(loginUser.getUserRole())){
            ThrowUtils.throwIf(true,ErrorCode.NO_AUTH_ERROR);
        }
        Surveys s = surveysService.getById(surveyId);
        if (s == null){
            return ResultUtils.error(ErrorCode.OPERATION_ERROR,"模板不存在");
        }
        boolean b = surveysService.removeById(surveyId);
        if (!b){
            return ResultUtils.error(ErrorCode.OPERATION_ERROR,"删除失败");
        }
        return ResultUtils.success(b);
    }

    /**
     * 删除审核记录
     * 仅限管理员
     */
    @PostMapping("/deleteAudit")
    public R<Boolean> deleteAudit(@RequestBody TemplateAudit templateAudit, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            ThrowUtils.notLoginError();
        }
        if (templateAudit == null || templateAudit.getId() == null){
            ThrowUtils.paramsError("参数错误");
        }
        if (!ADMIN_ROLE.equals(loginUser.getUserRole())){
            ThrowUtils.throwIf(true,ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = templateService.removeById(templateAudit.getId());
        if (!b){
            return ResultUtils.error(ErrorCode.OPERATION_ERROR,"删除失败");
        }
        return ResultUtils.success(b);
    }
}
